package com.weic.easycache.http.proxy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import com.weic.easycache.http.Http;

import android.util.Log;

/**HTTP请求处理器**/
public class HttpRequestHandler extends Thread {
	public static final boolean LOG = false;
	public final String LOG_TAG = "[HttpRequestHandler]";
	public String MSG;

	private String host;
	private String referer;
	private int port;
	private int timeout;
	final Socket socket;

	HttpRequestHandler(Socket socket, String host, int port, String referer, int timeout) {
		this.socket = socket;
		this.host = host;
		this.port = port;
		this.referer = referer;
		this.timeout = timeout;
		setDaemon(true);
	}

	@Override
	public void run() {
		MSG = currentThread().toString();
		Log.d(LOG_TAG, MSG+"start---------------");

		List<String> headerList = new ArrayList<String>();

		BufferedReader reader = null;
		OutputStreamWriter writer = null;
		boolean hasReferer = false;
		try {
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			writer = new OutputStreamWriter(socket.getOutputStream());	//对头的输出采用默认的编码

			socket.setSoTimeout(timeout);

			String line = null;
			boolean ignore = false;
			String uri = null;
			do {
				line = reader.readLine();
				line = line==null ? Http.CRLF : line+Http.CRLF;
				if(LOG) Log.i(LOG_TAG, MSG+line);
				//解析请求字符串并转发
				if(line.startsWith(Http.GET)) {
					String[] gets = line.split(" +");
					uri = gets[1];	//匹配任意多个空格
					if(LOG) Log.i(LOG_TAG, MSG+"Uri:"+uri);
					//请求图标的或默认页的
					if(uri.equals("/favicon.ico") || uri.equals("/")) {
						if(host==null || host.equals("")) {
							ignore = true;
							break;
						}
					}else if(uri.indexOf("?")>0) {	//解析host参数和referer参数，如果有"?"则必然大于0，因为第一个是"/"
						String[] params = uri.split("[?]");	//这里不能直接写问号，否则解析正则表达式异常
						int len = params.length;
						if(len>1) {
							uri = params[0] + "?";
							params = params[1].split("&");
							len = params.length;
							String[] kv = null;
							for(int i=0; i<len; ++i) {	//分离出host和referer参数
								if(params[i].toLowerCase().startsWith(Http.K_host)) {
									kv = params[i].split("=");
									if(kv.length>1) {
										host = kv[1];
										if(host.indexOf(":")>0) {
											kv = host.split(":");
											host = kv[0];
											if(kv.length>1) {
												try{
													port = Integer.valueOf(kv[1].trim());
													if(LOG) Log.i(LOG_TAG, MSG+"[param]port:"+port);
												}catch(Exception e){}
											}
										}
										if(LOG) Log.i(LOG_TAG, MSG+"[param]host:"+host);
									}
								}else if(params[i].toLowerCase().startsWith(Http.K_referer)) {
									kv = params[i].split("=");
									if(kv.length>1) {
										referer = kv[1];
										if(LOG) Log.i(LOG_TAG, MSG+"[param]referer:"+referer);
									}
								}else if(params[i].toLowerCase().startsWith(Http.K_resourse) &&
										!params[i].equalsIgnoreCase(Http.RESOURSE_sample)) {
									//解析key_resourse=http:/1163/1163-1-1-2012-62304_480/1163-1-1-2012-62304_480-36.ts
									kv = params[i].split("=");
									if(kv.length>1) {
										String resourse = kv[1];
										if(LOG) Log.i(LOG_TAG, MSG+"[param]resourse:"+resourse);
										if(resourse.startsWith("http:/")) {	//后面多个“/”可以不用管
											resourse = resourse.substring(6);
										}
										String old = uri.substring(uri.indexOf("/", 1)+1, uri.indexOf("?"));
										uri = uri.replaceFirst(old, resourse);
									}
								}else {
									uri += params[i] + "&";
								}
							}
							uri = uri.substring(0, uri.length()-1);
							if(LOG) Log.i(LOG_TAG, MSG+"[param]uri:"+uri);
							len = gets.length;
							line = "";
							for(int i=0; i<len; ++i) {
								if(i==1) {
									line += uri +" ";
								}else {
									line += gets[i]+" ";
								}
							}
							line = line.trim()+Http.CRLF;
						}
					}
					if(host==null || host.equals("")) {
						ignore = true;
						break;
					}
				}else if(line.startsWith(Http.HOST)) {
					line = Http.HOST+host+Http.CRLF;
				}else if(line.startsWith(Http.REFERER)) {
					hasReferer = true;
					if(referer!=null && !referer.equals("")) {
						line = Http.REFERER+referer+Http.CRLF;
					}
				}
				headerList.add(line);
			}while(!line.equals(Http.CRLF));
			if(ignore) {
				writer.write("HTTP/1.0 200 OK\r\n");
				writer.write("Connection: close\r\n");
				writer.write(Http.CRLF);
				writer.write("host参数不能为空!");
				writer.flush();	//如果暂不关闭writer则最好先flush，否则client端可能读不到数据
				ignore = false;

				Log.d(LOG_TAG, MSG+"ignored------");
				try {
					Log.d(LOG_TAG, MSG+"close------");
					//必须先关闭out，再关闭in，否则异常
					writer.close();
					reader.close();
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else {
				if(!hasReferer) {
					if(referer!=null && !referer.equals("")) {
						line = Http.REFERER+referer+Http.CRLF;
						int len = headerList.size();
						if(len>3) headerList.add(len-1, line);
						hasReferer = false;
					}
				}
				//转发但是不要关闭socket
				new HttpStreamJoiner(socket, headerList.toArray(new String[0]), host, port).start();
				Log.d(LOG_TAG, MSG+"end, success dispatched!------");
			}
		} catch (IOException e) {
			try {
				Log.e(LOG_TAG, MSG+"end------");
				//必须先关闭out，再关闭in，否则异常
				if(writer != null) writer.close();
				if(reader != null) reader.close();
				socket.close();
			} catch (IOException ee) {
				ee.printStackTrace();
			}
			e.printStackTrace();
		}
	}
}